#!/bin/bash
function Usage() {
    echo "Usage : $0"
}

if [[ $# -ge 1 ]];then
    Usage
    exit 1
fi

threshold=50

eval `ps -aux --sort=-%cpu -h | awk -v yu=${threshold} -v num=0 '{if ($3 < yu) {exit} else {num++;printf("cpuprocid["num"]=%d;", $2)}} END {printf("cpunum=%d;", num)}'`


eval `ps -aux --sort=-%mem -h | awk  -v yu=${threshold} -v num=0 '{if ($4 < yu) {exit} else {num++;printf("memprocid["num"]=%d;", $2)}} END {printf("memnum=%d;", num)}'`


if [[ ${cpunum} -gt 0 || ${memnum} -gt 0 ]];then
    sleep 5
else
    exit 0
fi

NowTime=`date +"%Y-%m-%d %H:%M:%S"`


if [[ ${cpunum} -gt 0 ]];then
    cnt=0
    for i  in ${cpuprocid[*]};do
        let cnt+=1
        eval `ps -aux -q $i -h | awk -v yu=${threshold} -v num=${cnt} \
            '{if ($3 < yu) {exit} else {printf("cpuprocname["num"]=%s;cpuprocid1["num"]=%d;cpuprocuser["num"]=%s;cpuproccpu["num"]=%s;cpuprocmem["num"]=%s;", $11, $2, $1, $3, $4)}} END {printf("cpuchecknum=%d;", num)}'`
    done
fi


if [[ ${memnum} -gt 0 ]];then
    cnt=0
    for i  in ${memprocid[*]};do
        let cnt+=1
        eval `ps -aux -q $i -h | awk -v yu=${threshold} -v num=${cnt} \
            '{if ($4 < yu) {exit} else {printf("memprocname["num"]=%s;memprocid1["num"]=%d;memprocuser["num"]=%s;memproccpu["num"]=%s;memprocmem["num"]=%s;",\
            $11, $2, $1, $3, $4)}} END {printf("memchecknum=%d;", num)}'`
    done
fi

if [[ ${cpuchecknum} -gt 0 ]];then
    for ((i = 1; i <= ${cpuchecknum}; i++));do
        echo "${NowTime} ${cpuprocname[$i]} ${cpuprocid1[$i]} ${cpuprocuser[$i]} ${cpuproccpu[$i]}% ${cpuprocmem[$i]}%"
    done
fi

if [[ ${memchecknum} -gt 0 ]];then
    for ((i = 1; i <= ${memchecknum}; i++));do
        echo "${NowTime} ${memprocname[$i]} ${memprocid1[$i]} ${memprocuser[$i]} ${memproccpu[$i]}% ${memprocmem[$i]}%"
    done
fi
